-- UIArtifactEffect
-- Created by huanghr
-- 神器合成界面

UIArtifactEffect = class("UIArtifactEffect", function()
    return cc.Layer:create();
end);

function UIArtifactEffect.create(classId, type)
    return UIArtifactEffect.new(classId, type);
end

-- 漩涡的半径
local RADIUS = 40;

-- 构造函数
function UIArtifactEffect:ctor(classId, type)
    self:setName("UIArtifactEffect");
    local node = cc.CSLoader:createNode("layout/hero/FoodCompound.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.classId = classId;

    self.type = type;
    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化窗口
    self:initForm();

    -- 播放
    self:play();

    -- 适配
    self:resize();
end

-- 适配
function UIArtifactEffect:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- 飞行的材料节点
    AlignM.alignToCenter(node, "fly_node");
end

-- 注册点击事件
function UIArtifactEffect:registerTouchEvent()
    local bgImage = findChildByName(self.node, "bg/bgImg");
    local function onBgClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            -- 关闭本界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIArtifactEffect");
        end
    end
    bgImage:addTouchEventListener(onBgClick);

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIArtifctEffect");
            -- show bottom
            if self.type == "compound" then
                local uiArtifactChoose = UIMgr.getCurrentScene():getFormByName("UIArtifactChoose");
                if uiArtifactChoose then
                    uiArtifactChoose:playUpgradeEffect(self.classId);
                end
            else

            end

             local uiArtifactUpgrade = UIMgr.getCurrentScene():getFormByName("UIArtifactUpgrade");
                if uiArtifactUpgrade then
                    uiArtifactUpgrade:redraw();

                end
        end
    end);

end

-- 初始化窗口
function UIArtifactEffect:initForm()
    -- 初始化标题
    local CT = findChildByName(self.node, "CT");
    local titleLabel = findChildByName(CT, "title_node/title");
    local title;
    if self.type == "compound" then
        title = getLocStr("artifact_compound");
    else
        title = getLocStr("artifact_upgrade_title2");
    end
    local kerning, kerning2 = 0, 0;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning, kerning2 = -6, -5;
    end
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_HUGE, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, kerning);
    titleLabel:setString(title);
    titleLabel:setVisible(false);

    -- 神器名称
    local nameLabel = findChildByName(CT, "name_node/food_name");

    local name = ItemM.query(self.classId, "name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_BEIGE, true, kerning2);
    nameLabel:setString(name);
    nameLabel:setVisible(false);
end

-- 播放
function UIArtifactEffect:play()
    -- 音效
    AudioM.playFx("admix_food");
    local flyNode = findChildByName(self.node, "fly_node");

    local h = cc.Director:getInstance():getOpenGLView():getFrameSize().height;
    local w = cc.Director:getInstance():getOpenGLView():getFrameSize().width;
    local ids = {};
    for i = 1, 3 do
        table.insert(ids, self.classId + 200);
    end
    local count = #ids;
    local materialNodes = {};

    if count == 1 then
        -- 仅一种食材，从正中间飞入
        local midNode = cc.Node:create();
        midNode:setPosition(0, h/2);
        flyNode:addChild(midNode);
        table.insert(materialNodes, { "mid", midNode });

    elseif count == 2 then
        -- 有两种食材，从左右两边飞入
        local rightNode = cc.Node:create();
        rightNode:setPosition(w/2, h/2);
        flyNode:addChild(rightNode);
        table.insert(materialNodes, { "right", rightNode });

        local leftNode = cc.Node:create();
        leftNode:setPosition(-w/2, h/2);
        flyNode:addChild(leftNode);
        table.insert(materialNodes, {"left", leftNode });

    elseif count == 3 then
        -- 有三种食材，从右、左、中三端飞入
        local rightNode = cc.Node:create();
        rightNode:setPosition(w/2, h/2);
        flyNode:addChild(rightNode);
        table.insert(materialNodes, { "right", rightNode });

        local leftNode = cc.Node:create();
        leftNode:setPosition(-w/2, h/2);
        flyNode:addChild(leftNode);
        table.insert(materialNodes, { "left", leftNode });

        local midNode = cc.Node:create();
        midNode:setPosition(0, h/2);
        flyNode:addChild(midNode);
        table.insert(materialNodes,  { "mid", midNode });
    else
        error("暂不支持%d种食材的飞入动画。", count);
        return;
    end

    -- 飞入的终点位置
    local toPos = cc.p(0, - 80);

    local flyDuration    = 0.4;   -- 飞入时间
    local rotateDelay    = 0.1;   -- 到达目标后，短暂停顿的时间
    local rotateDuration = 0.3;   -- 旋转时间
    local produceDuration = 0.4;  -- 加工时间
    local flyInterval    = 0.1;   -- 依次飞行的时间间隔

    local foodNode = findChildByName(self.node, "CT/food_node");

    for i, arr in pairs(materialNodes) do
        local direction = arr[1];
        local materialNode = arr[2];
        local classId = ids[i];
        local icon = ItemM.query(classId, "icon");
        local iconPath = getItemIconPath(icon);
        local image = ccui.ImageView:create(iconPath);
        materialNode:addChild(image);
        local posX, posY;

        local deltaX = RADIUS * math.cos(30*(math.pi/180));
        local deltaY = RADIUS * math.sin(30*(math.pi/180));

        if direction == "left" then
            -- 左
            posX = -deltaX;
            posY = -deltaY;
            image:setPosition(posX, posY);
        elseif direction == "mid" then
            -- 中
            posX = 0;
            posY = RADIUS;
            image:setPosition(posX, posY);
        else
            -- 右
            posX = deltaX;
            posY = -deltaY;
            image:setPosition(posX, posY);
        end

        -- 飞入（轨迹为抛物线）
        --local moveTo = cc.EaseInOut:create(cc.MoveTo:create(flyDuration, toPos), 2.0);
        local moveTo = cc.EaseInOut:create(cc.JumpTo:create(flyDuration, toPos, 100, 1), 2.0);

        trace("UIArtifactEffect", "from (%d, %d), to (%d, %d)",
            materialNode:getPositionX(), materialNode:getPositionY(),
            toPos.x, toPos.y);

        -- 旋转
        local rotateBy = cc.RotateBy:create(rotateDuration, -180);

        -- 缩小
        local scaleTo = cc.ScaleTo:create(rotateDuration, 0.8);

        -- 淡出
        local fadeOut = cc.FadeOut:create(rotateDuration);

        local callFunc = cc.CallFunc:create(function()
            -- 移除食材节点
            flyNode:removeChild(materialNode);
        end);

        materialNode:runAction(cc.Sequence:create(
            cc.DelayTime:create(flyInterval * (i - 1)),    -- 将飞行时间错开
            moveTo,                                        -- 飞入
            cc.DelayTime:create(rotateDelay),              -- 旋转前短暂停顿
            cc.Spawn:create(rotateBy, scaleTo, fadeOut),   -- 旋转、缩小、淡出同时进行
            callFunc));
    end

    -- 2.播放加工特效
    local effectNode = findChildByName(self.node, "CT/effect_node");
    local function produce()
        playEffect(effectNode, 1184);
    end
    local totalTime = flyInterval*(#materialNodes - 1) + flyDuration + rotateDelay;
    performWithDelay(self, produce, totalTime);


    local classId = self.classId;
    local function generate()
        -- 播放光圈动画
        local function playLightAnim()
            local lightImg = findChildByName(self.node, "CT/food_light");
            lightImg:setVisible(true);

            -- 旋转
            local cycleTime = 10;
            local rotateBy = cc.RotateBy:create(cycleTime, 360);

            -- 淡出变化
            local initFadeTime = 1;
            local fadeTo = cc.FadeTo:create(initFadeTime, 125);

            -- 缩小
            local scaleTo = cc.ScaleTo:create(0.8, 0.6);

            lightImg:runAction(cc.Spawn:create(rotateBy, fadeTo, scaleTo));

            -- 等到首次淡出动作结束时，开始重复淡入、淡出、旋转
            local function repeatFadeAndRotate()
                local inTime  = 1;   -- 淡入时间
                local outTime = 1;   -- 淡出时间
                local fadeIn  = cc.FadeTo:create(inTime, 255);
                local fadeOut = cc.FadeTo:create(outTime, 100);

                -- 计算旋转一圈需要淡入、淡出多少次
                local times = cycleTime / (inTime + outTime);
                local fadeRepeat = cc.Repeat:create(cc.Sequence:create(fadeIn, fadeOut), times);

                rotateBy = cc.RotateBy:create(cycleTime, 360);

                -- 重复淡入、淡出、旋转
                local actionSpawn = cc.Spawn:create(fadeRepeat, rotateBy);
                local actionForever = cc.RepeatForever:create(actionSpawn);
                lightImg:runAction(actionForever);
            end

            performWithDelay(lightImg, repeatFadeAndRotate, initFadeTime);
        end

        playLightAnim();

        -- 星光闪烁
        playEffect(effectNode, 1191);

        -- 显示食物图标
        local productImg = ccui.ImageView:create();
        foodNode:addChild(productImg);
        local icon = ItemM.query(classId, "icon");
        productImg:loadTexture(getItemIconPath(icon));

        -- 食物出现
        local upTime   = 0.2;
        local downTime = 0.1;
        local function appear()
            -- 先放大再缩小
            local oldScale = foodNode:getScale();
            local scaleUp = cc.ScaleTo:create(upTime, 2.0 * oldScale);
            local scaleDown = cc.ScaleTo:create(downTime, 0.9 * oldScale);
            foodNode:runAction(cc.Sequence:create(scaleUp, scaleDown));
        end
        appear();

        -- 食物呼吸
        local function breath()
            playBubbleAnima(foodNode, false);
        end

        performWithDelay(foodNode, breath, upTime + downTime);
    end

    totalTime = totalTime + rotateDuration + produceDuration;
    performWithDelay(self, generate, totalTime);

    -- 合成音效
    AudioM.playFx("admix_food");

    -- 4.播放合成成功提示
    performWithDelay(self, self.playCompoundTip, totalTime);
end

-- 播放合成成功提示
function UIArtifactEffect:playCompoundTip()
    local CT = findChildByName(self.node, "CT");
    local titleLabel = findChildByName(CT, "title_node/title");
    local title = titleLabel:getString();
    local len = string.getWCharCount(title);

    -- 加速因子
    local accFactor = 2;

    if getLang() ~= "zh" and getLang() ~= "tw" then
        accFactor = 0.2 * len;
    end

    local titleFlyIn = cc.CallFunc:create(function()
        -- 标题飞入
        titleLabel:setVisible(true);
        local parentNode = titleLabel:getParent();
        setTextRotate(string.getWCharCount(title), titleLabel, parentNode, 360, accFactor);
    end);

    titleLabel:runAction(titleFlyIn);

    -- 显示食物名称
    local nameLabel = findChildByName(CT, "name_node/food_name");

    local nameFlyIn = cc.CallFunc:create(function()
        -- 食物名称飞入
        nameLabel:setVisible(true);
        local parentNode = nameLabel:getParent();
        local name = nameLabel:getString();
        setTextRotate(string.getWCharCount(name), nameLabel, parentNode, 360, accFactor);
    end);

    nameLabel:runAction(cc.Sequence:create(cc.DelayTime:create(0.5), nameFlyIn));
end